package com.yr.visa.proxy.ctx;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yr.visa.connection.ConfigManager;
import com.yr.visa.connection.ConnectionInvoker;
import com.yr.visa.util.IdFactory;
import com.yr.visa.util.StringUtil;

public class Brower {

	private static Logger log = LoggerFactory.getLogger(Brower.class);
	private WebDriver driver = null;
	private ConfigManager manager = null;
	private ConnectionInvoker invoker;
	private int times;
	public Brower(ConfigManager manager) {
		this(manager, null);

	}

	public Brower(ConfigManager manager, Set<Cookie> cookies) {
		this.manager = manager;
		ArrayList<String> cliArgsCap = new ArrayList<String>();
		cliArgsCap.add("--web-security=false");
		cliArgsCap.add("--ssl-protocol=any");
		cliArgsCap.add("--ignore-ssl-errors=true");
		cliArgsCap.add("--load-images=no");
		cliArgsCap.add("--disk-cache=yes");

		DesiredCapabilities DesireCaps = new DesiredCapabilities();
		DesireCaps.setCapability("acceptSslCerts", true);
		DesireCaps.setJavascriptEnabled(true);
		DesireCaps.setCapability("phantomjs.page.settings.userAgent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
		DesireCaps.setCapability("phantomjs.page.customHeaders.User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
		DesireCaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
				manager.getCurrConfig().getPhantPath());
		DesireCaps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap);
		driver = new PhantomJSDriver(DesireCaps);
		driver.manage().window().maximize();
		driver.manage().timeouts().pageLoadTimeout(Integer.parseInt(manager.getCurrConfig().getLoadPageTimeout()), TimeUnit.SECONDS);
		driver.manage().timeouts().implicitlyWait(Integer.parseInt(manager.getCurrConfig().getElementGetTimeout()), TimeUnit.SECONDS);
		resetCookie(cookies);
	}

	public void loadUrl(String url){
		driver.get("https://online.immi.gov.au/elp/app?action=new&formId=VSS-AP-600");
		if(driver.getCurrentUrl().contains("login")){
			log.info("current url,{}",driver.getCurrentUrl());
			this.invoker.login();
			if(times ==0){
				throw new WcAccessException("重复尝试登陆失败");
			}
			times--;
			loadUrl(url);
		}
		times=3;
	}
	
	
	public void setConnectionInvoker(ConnectionInvoker invoker){
		this.invoker = invoker;
	}
	
	public String printScreen(String folder, String next) {
		if (StringUtil.isBlank(folder)) {
			folder = "tmp";
		}
		if (StringUtil.isBlank(next)) {
			next = "";
		}
		if (!manager.getSysConfig("isDebug").equals("true")) {
			return null;
		}

		File f = new File(this.manager.getCurrConfig().getImageSavePath(), folder);
		if (!f.exists()) {
			f.mkdirs();
		}
		String _saveFileName = next + "-" + IdFactory.getDateTimeRandomStr() + ".png";
		File saveFile = new File(f, _saveFileName);
		try {
			File scrFile = ((TakesScreenshot) this.getDriver()).getScreenshotAs(OutputType.FILE);
			FileUtils.copyFile(scrFile, saveFile);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return manager.getCurrConfig().getImageAccessUrl()+folder+"/"+_saveFileName;
	}

	public void resetCookie(Set<Cookie> cookies) {
		driver.get("https://online.immi.gov.au");

		// this.waitSecond(null, 5);
		driver.manage().deleteAllCookies();
		if (cookies != null) {
			for (Cookie c : cookies) {
				driver.manage().addCookie(c);
			}
		}
	}

	public WebElement waitSecond(By b, int second) {
		if (b == null) {
			try {
				Thread.sleep(second * 1000l);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		} else {
			WebDriverWait wait = new WebDriverWait(driver, second);
			return wait.until(ExpectedConditions.presenceOfElementLocated(b));
		}

	}

	public WebElement waitSecondToClick(By b, int second) {
		if (b == null) {
			try {
				Thread.sleep(second * 1000l);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		} else {
			WebDriverWait wait = new WebDriverWait(driver, second);
			return wait.until(ExpectedConditions.elementToBeClickable(b));
		}

	}

	public Set<Cookie> getCookie() {
		return driver.manage().getCookies();
	}

	public WebDriver getDriver() {
		return driver;
	}
	
	
	
}
